package com.lzb.interceptor;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import redis.clients.jedis.JedisCluster;

/**
 * 数据库表转换为redis缓存（对于耗时的查询，可以直接从缓存获取）
 * @author lizebin
 *
 */
//@Component(MngUserDBCacheInterceptor.BEAN_PACKAGE_NAME)
//@Aspect
public class MngUserDBCacheInterceptor implements Ordered {

	public static final String BEAN_PACKAGE_NAME = "com.lzb.interceptor.MngUserDBCacheInterceptor";
	@Resource(name = "jedisCluster")
	private JedisCluster jedisCluster;
	private final static String SPLITTING = ":";
	/**
	 * 后置通知
	 */
	private final String AFTER_RETURNING_POINTCUT_EXECUTION = "execution(* com.lzb..*Service.add*(..)) || "
			+ "execution(* com.lzb..*Service.insert*(..))";
	
	/**
	 * 返回后通知（After returning advice）： 在某连接点（join
	 * point）正常完成后执行的通知：例如，一个方法没有抛出任何异常，正常返回。
	 * @throws Exception 
	 * @throws SecurityException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 * */
	@AfterReturning(AFTER_RETURNING_POINTCUT_EXECUTION)
	public void afterReturning(JoinPoint pjp) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, Exception {
		//MySQL数据转化成redis缓存数据
		/*
		 * 原则:
		 *  key 表名：主键值（我觉得这个只要是业务唯一要素即可）：列名
     		value 列值
		 * */
		System.out.println(Thread.currentThread().getName() + " begin ");
		System.out.println(jedisCluster.getClusterNodes());
		MethodSignature signature = (MethodSignature) pjp.getSignature();
		//事务已提交，MngUser已含有id
		Object[] args = pjp.getArgs();
		if(null != args && args.length > 0) {
			Class[] paramsType = signature.getParameterTypes();
			Field[] fields = paramsType[0].getDeclaredFields();
			for(Field _field : fields) {
				String fieldName = _field.getName();
				String value = String.valueOf(paramsType[0].getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), new Class[0]).invoke(args[0], new Class[0]));
				if("id".equalsIgnoreCase(fieldName))continue;
				jedisCluster.set(paramsType[0].getSimpleName() 
						+ SPLITTING + String.valueOf(paramsType[0].getMethod("getId", new Class[0]).invoke(args[0], new Class[0])) 
						+ SPLITTING + _field.getName(), value);
			}
		}
		System.out.println(Thread.currentThread().getName() + " after ");
	}
	
	@Override
	public int getOrder() {
		return 2;
	}

}
